import config from './config.js'
// import video from './camera.js'
function msg(title = '', param={}){
	if(!title){
		return;
	}
	const duration = param.duration || 1500;
	const mask = param.mask || false;
	const icon = param.icon || 'none';
	
	let options = {
		title,
		duration,
		mask,
		icon
	}
	
	if(param.type){
	//	options.image = '/static/' + param.type + '.png';
	}
	uni.showToast(options);
}

function date(format, timeStamp){
	if(!timeStamp){
		return;
	}
	if(timeStamp.toString().length===10){
		timeStamp = timeStamp * 1000;
	}
	// console.log("tools==",timeStamp)
	timeStamp = Number(timeStamp);
	let date = new Date(timeStamp),
		Y = date.getFullYear(),
		m = date.getMonth() + 1,
		d = date.getDate(),
		H = date.getHours(),
		i = date.getMinutes(),
		s = date.getSeconds();
	
	m = m < 10 ? '0' + m : m;
	d = d < 10 ? '0' + d : d;
	H = H < 10 ? '0' + H : H;
	i = i < 10 ? '0' + i : i;
	s = s < 10 ? '0' + s : s;
	return format.replace(/[YmdHis]/g, key=>{
		return {Y,m,d,H,i,s}[key];
	});
}

/**
 * 节流原理：在一定时间内，只能触发一次
 * 
 * @param {Function} func 要执行的回调函数 
 * @param {Number} wait 延时的时间
 * @param {Boolean} immediate 是否立即执行
 * @return null
 * this.throttle(this.getResult, this.timeout, this.immediate);
 */
let timer, flag;
function throttle(func, wait = 1200, immediate = true) {
	if (immediate) {
		if (!flag) {
			flag = true;
			// 如果是立即执行，则在wait毫秒内开始时执行
			typeof func === 'function' && func();
			timer = setTimeout(() => {
				flag = false;
			}, wait);
		}
	} else {
		if (!flag) {
			flag = true
			// 如果是非立即执行，则在wait毫秒内的结束处执行
			timer = setTimeout(() => {
				flag = false
				typeof func === 'function' && func();
			}, wait);
		}
		
	}
}

function throttleFn(fn, gaptime) {
	if (gaptime == null || gaptime == undefined) {
		gaptime = 2000
	}
	let _lastTime = null
	return function() {
		let _nowTime = +new Date()
		if (_nowTime - _lastTime > gaptime || !_lastTime) {
			fn.apply(this, arguments)
			_lastTime = _nowTime
		}
	}
}


/**
 * 防抖原理：一定时间内，只有最后一次操作，再过wait毫秒后才执行函数
 * 
 * @param {Function} func 要执行的回调函数 
 * @param {Number} wait 延时的时间
 * @param {Boolean} immediate 是否立即执行 
 * @return null
 * this.debounce(this.getResult, this.timeout, this.immediate);
 */
let timeout = null;
function debounce(func, wait = 500, immediate = false) {
		// 清除定时器
		if (timeout !== null) clearTimeout(timeout);
		// 立即执行，此类情况一般用不到
		if (immediate) {
			var callNow = !timeout;
			timeout = setTimeout(function() {
				timeout = null;
			}, wait);
			if (callNow) typeof func === 'function' && func();
		} else {
			// 设置定时器，当最后一次操作后，timeout不会再被清除，所以在延时wait毫秒后执行func回调方法
			timeout = setTimeout(function() {
				typeof func === 'function' && func();
			}, wait);
		}
	}

function inAction(fn, that, timeout = 2000){
	if(that['in' + fn]){
		return true
	}
	that['in' + fn] = true;
	setTimeout(()=>{
		that['in' + fn] = false;
	}, timeout)
	return false;
}
function match(str, type, msgTxt){
	let exp = '';
	switch(type){
		case 'mobile':
			if(str === ''){
			    msg('请填写手机号码');
				return false;
			}
			exp = /(^1[3|4|5|6|7|8|9][0-9]{9}$)/; //手机号
			if(!exp.test(str)){
			    msg('手机号码格式不正确');
				return false;
			}
			break;
		case 'pwd':
			if(str === ''){
			    msg('请填写密码');
				return false;
			}
			//必须加break; 否则pwd校验正确后会进入 case 'code'
			break;
		case 'code':
				if(str === ''){
				    msg('请填写验证码');
					return false;
				}
				if(!/^[0-9]+$/.test(str)){
				    msg('验证码不正确');
					return false;
				}
			break;
		case 'idcard':
				if(str === ''){
				    msg('请填写身份证号码');
					return false;
				}
				if(!/^(\d{17}[\d|x|X]|\d{15})$/.test(str)){
				    msg('请输入正确身份证号');
					return false;
				}
			break;
		case 'nonull':
		// console.log("nonull==",str);
		   if( !str ){
		       msgTxt && msg(msgTxt);
		   	return false;
		   }
		   //必须加break; 否则pwd校验正确后会进入 case 'code'
		   break;
	}
	return true;
}

// 返回上一页
const prePage = (num=1) => {
	let pages = getCurrentPages();
	let prePage = pages[pages.length -1- num];
	// #ifdef H5
	return prePage;
	// #endif
	return prePage.$vm;
}


// 上传图片--注按需要对res处理 JSON.parse()
function uploadImg(formData){
	return new Promise((resolve,reject)=>{
		uni.chooseImage({
			count:1,
			success(chooseImageRes){
				// resolve(chooseImageRes.tempFilePaths[0]);
				const tempFilePaths = chooseImageRes.tempFilePaths[0];
				 // localStorage.getItem('token');
				const token = uni.getStorageSync('token')
				uni.showLoading({
					title: '请稍后..',
					mask: true,
				})
				uni.uploadFile({
					url:config.uploadImgUrl,
					filePath: tempFilePaths,
					name: 'file',
					formData:formData,
					header: {
						'token':token,
					},
					success:(res)=>{
						//需要JSON.parse
						// console.log('upload res---',res);
						let data = JSON.parse(res.data);
						if(!data || data.code !== 1 ){
							msg('上传失败');
							reject();
							return;
						}
						//即为全路径地址fullurl,url
						resolve(data.data.fullurl);
					},
					fail:(err)=>{
						// console.log('err--',err);
						// this.$tools.msg(JSON.stringify(err));
						msg('上传失败');
						reject();
					},
					complete:()=> {
						uni.hideLoading();
					},
				})
			},
			fail(err){
				// msg('打开相册失败');
				reject(err)
			}
		})
	})
}
function uploadVideoOld(formData={}){
		return new Promise((resolve,reject)=>{
			uni.chooseVideo({
				maxDuration: 300,
				success(chooseImageRes){
					// resolve(chooseImageRes.tempFilePaths[0]);
					const tempFilePaths = chooseImageRes.tempFilePath;
					 // localStorage.getItem('token');
					const token = uni.getStorageSync('token')
					uni.showLoading({
						title: '请稍后..',
						mask: true,
					})
					uni.uploadFile({
						url:config.uploadImgUrl,
						filePath: tempFilePaths,
						name: 'file',
						formData:formData,
						header: {
							'token':token,
						},
						success:(res)=>{
							//需要JSON.parse
							// console.log('upload res---',res);
							let data = JSON.parse(res.data);
							if(!data || data.code !== 1 ){
								uni.showModal({
									title:'data.code !== 1',
									content: JSON.stringify(data)
								})
								uni.$tools.msg('上传失败');
								return;
							}
							//即为全路径地址fullurl,url
							// data.get_carvideo = data.data.fullurl
							resolve(data.data.fullurl)
						},
						fail:(err)=>{
							// console.log('err--',err);
							// this.$tools.msg(JSON.stringify(err));
							uni.showModal({
								title:'error',
								content: JSON.stringify(err)
							})
							uni.$tools.msg('上传失败');
							reject();
						},
						complete:()=> {
							uni.hideLoading();
						},
					})
				},
				fail(err){
					// // msg('打开相册失败');
					// uni.$tools.msg('选择失败');
					console.log("err===",err);
					reject();
				}
			})
	    })
}
/**
 * oss上传
 */
function _getSuffix(filename) {
	let pos = filename.lastIndexOf('.');
	let suffix = '';
	if (pos != -1) {
		suffix = filename.substring(pos);
	}
	return suffix;
}
function getFileName(filename) {
	return (
		'user_dir_' +
		new Date().getTime() +
		Math.random()
			.toString(36)
			.substring(3, 20) +
		_getSuffix(filename)
	);
}

function uploadVideo() {
	return new Promise(async (resolve, reject) => {
		const {data:param} = await uni.$request('basedata.signedUrl');
		const {accessid,policy,signature,bucket,fileurl} = param;
		uni.chooseVideo({
			// sourceType: ['album', 'camera'], // album 从相册选视频，camera 使用相机拍摄
			// maxDuration: 60, // 拍摄视频最长拍摄时间，单位秒。最长支持60秒
			// camera: 'back',//默认拉起的是前置或者后置摄像头，默认back
			compressed: false,//是否压缩所选择的视频文件
			maxDuration: 300,
			success: function(res){
				// console.log('wxUploadVideo----',res)
				var filePath = res.tempFilePath;
				let filename = getFileName(filePath);
				// var filename = filePath.substr(filePath.lastIndexOf('/') + 1);
				// var oName= res.tempFile.name || ''
				// var filename = Date.now() + Math.floor(Math.random()) + oName.substr(filePath.lastIndexOf('.') + 1);
				const token = uni.getStorageSync('token')
				uni.showLoading({
					title: '请稍后..',
					mask: true,
				})
				uni.uploadFile({
					url: bucket, // 开发者服务器的URL。
					filePath: filePath,
					name: 'file', // 必须填file。
					header: {
						'token':token,
					},
					formData: {
						key: fileurl+filename,
						// ...param,
						OSSAccessKeyId:accessid,
						policy,
						signature,
						// OSSAccessKeyId: _config.ossKey,
						// policy,
						// signature,
						// 'x-oss-security-token': securityToken // 使用STS签名时必传。
					},
					success: (res) => {
						console.log('success',res);
						if (res.statusCode === 204) {
							   // console.log('上传成功204',res);
							// let data = JSON.parse(res.data);
							// if(!data || data.code !== 1 ){
							// 	// uni.showModal({
							// 	// 	title:'data.code !== 1',
							// 	// 	content: JSON.stringify(data)
							// 	// })
							// 	uni.$tools.msg('上传失败');
							// 	reject();
							// 	return;
							// }
							let fullurl= bucket+'/'+fileurl+filename
							resolve(fullurl);
						}else{
							reject();
						}
				    },
				    fail: err => {
						console.log(err);
						uni.$tools.msg('上传失败');
						reject();
				    },
					complete:()=> {
						uni.hideLoading();
					},
			    });
			},
			fail: (err)=>{
				console.log("chooseVideo err",err);
			}
		});
	})
}

///**详情页处理富文本 details仅是变化替换部分a.replace(/<text>(abc)<\/text>/,function(match,$1) $1=abc---------------------------------------------------------------------- */
const replaceDetail = (details = '') => {
	//newContent仅是details替换后内容;
  let newContent = details.replace(/<img[^>]*>/gi, function (match, capture) { //去除三标签
    match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
    match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
    match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
    return match;
  });
  newContent = newContent.replace(/<br[^>]*\/>/gi, '');
  newContent = newContent.replace(/<img/gi, '<img style="max-width:100%;height:auto;display:block;margin:0 auto;"');
  return newContent;
}

// 查看单张图片
function previewImg(urls,idx=0){
	uni.previewImage({
		current: idx,
		urls: urls
	})
}

//单个授权,针对定位await api.checkDeviceAuthorize('scope.userLocation','请开启定位,方便司机到达您的位置');
let hasOpenDeviceAuthorizeModal = false;
function checkDeviceAuthorize(scope,tipText) {
	if (hasOpenDeviceAuthorizeModal) {
		return
	}
	hasOpenDeviceAuthorizeModal = true
	
	return new Promise((resolve, reject) => {
		uni.getSetting().then((result) => {
			// this.authorizeCamera = result.authSetting['scope.camera']
			console.log('getSetting 查看所有授权',result);
			let authSetting = result['authSetting'];
			if (authSetting[scope]) {
				// console.log('getSetting 已授权',result);
				// 授权成功
				resolve({hasScoped:true})
				hasOpenDeviceAuthorizeModal = false
			} else {
				// 没有授权，弹出授权窗口
				// 注意： wx.authorize 只有首次调用会弹框，之后调用只返回结果，如果没有授权需要自行弹框提示处理
				// console.log('getSetting 查询没有授权，uni.authorize发起授权')
				uni.authorize({
					scope: scope,
					success: (res) => {
						// console.log('authorize ok', res)
					    resolve({initAuth:true})
						hasOpenDeviceAuthorizeModal = false
					},
					fail: (err) => {
						// console.log('authorize err 弹层提示', err)
						openConfirm(scope,tipText,(isTrue)=>{
							if(isTrue){
								resolve({popAuth:true})
								// reject(new Error('popAuth:true but onShow ok')); //onShow会得新调用
								hasOpenDeviceAuthorizeModal = false
							}else{
								reject(new Error('authorize fail'))
								hasOpenDeviceAuthorizeModal = false
							}
							
						})
					}
				})
			}
		})
	})
};
function openConfirm(scope,tipText,callback) {
	return uni.showModal({
		content: tipText,
		confirmText: '确认',
		cancelText: '取消',
		success: (res) => {
			// 点击“确认”时打开设置页面
			if (res.confirm) {
				// console.log('用户点击确认')
				uni.openSetting({
					success: (res) => {
						// console.log("wx.openSetting success res..",res)
						if(typeof callback == 'function' && res.authSetting[scope]==true){
							callback(true);
						}
					},
					fail:()=>{
						callback(false)
					}
				})
			} else {
				// console.log('用户点击取消')
				callback(false)
			}
		},
	})
};


export default {
	msg,
	date,
	throttle,
	throttleFn,
	debounce,
	inAction,
	match,
	prePage,
	replaceDetail,
	uploadImg,
	uploadVideo,
	// wxUploadVideo,
	previewImg,
	// toDayHHmmss,
	checkDeviceAuthorize,
}


//处理时间 date如秒去1000
// function toDayHHmmss (date) {
//    var time;
//    var day = parseInt(date / ( 60 * 60 * 24)) 
//    var hours = parseInt((date % ( 60 * 60 * 24)) / ( 60 * 60));
//    var minutes = parseInt((date % ( 60 * 60)) / ( 60));
//    var seconds = (date % ( 60));
//    time = (hours < 10 ? ('0' + hours) : hours) + ':' + (minutes < 10 ? ('0' + minutes) : minutes) + ':' + (seconds < 10 ? ('0' + seconds) : seconds);
//    if(day>0){
// 	   time = day + '天 '+time;
//    }
//    return time;
// }


